//
//  CoinImageViewModel.swift
//  Crypto
//
//  Created by DaleGuo on 2023/9/22.
//

import Combine
import Foundation
import SwiftUI

class CoinImageViewModel: ObservableObject {
    @Published var image: UIImage? = nil
    @Published var isLoading: Bool = false

    private var cancelables = Set<AnyCancellable>()

    private let coin: CoinModel
    private let coinImageService: CoinImageService

    init(coin: CoinModel) {
        self.coin = coin
        self.coinImageService = CoinImageService(coin: coin)
        addSubscriber()
        self.isLoading = true
    }

    func addSubscriber() {
//        vm的image要去订阅service中的image
        coinImageService.$image
            .sink { [weak self] returnedImage in
                self?.isLoading = false
                self?.image = returnedImage
            }
            .store(in: &cancelables)
    }
}
